package com.boil.qz.safekavass.weixin.controller;

import com.boil.exception.RequestParamException;
import com.boil.pojo.ResultVo;
import com.boil.qz.safekavass.service.WeixinUserService;
import com.boil.qz.safekavass.weixin.request.param.BindPhoneParam;
import com.boil.qz.safekavass.weixin.util.WeixinUtils;
import com.boil.util.BaseController;
import com.boil.util.Constants;
import com.boil.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;

/**
 * Created by ChenYong on 2017-07-10.
 * <br>
 * 绑定 Controller。
 */
@Controller
@RequestMapping("/weixin/bind")
public class BindController extends BaseController {
    /**
     * 注入微信用户 Service
     */
    @Autowired
    private WeixinUserService weixinUserService;

    /**
     * 绑定手机号。
     *
     * @param model  模型
     * @param param  绑定手机号的请求参数
     * @param errors 请求参数的校验结果
     * @return 结果页面
     */
    @RequestMapping(method = RequestMethod.POST, value = "/phone.html")
    public String bindPhone(Model model, @Valid BindPhoneParam param, BindingResult errors) {
        // 结果 Vo
        ResultVo resultVo = new ResultVo();

        model.addAttribute(Constants.RESULT_VO, resultVo);

        try {
            // 判断请求参数是否校验通过
            Utils.hasRequestParamError(resultVo, errors);

            weixinUserService.doBindPhone(resultVo, param);
        } catch (RequestParamException e) {
            resultVo = e.getResultVo();

            resultVo.setResultMsg(String.format("抱歉，绑定手机号失败，原因：%s", e.getMessage()));
        } catch (Exception e) {
            log.error("微信绑定手机号出现异常：{}", e);

            resultVo.setResultCode(Constants.SYS_ERROR);
            resultVo.setResultMsg(String.format("抱歉，绑定手机号失败，原因：%s", e.getMessage()));
        }

        resultVo.setResult(String.format(WeixinUtils.URL_CONNECT_OAUTH2_AUTHORIZE, //
                WeixinUtils.APP_ID, //
                Constants.URL_ENCODE_WEIXIN_WEBPAGE_AUTHORIZE_SNSAPI_USERINFO, //
                WeixinUtils.SCOPE_SNSAPI_USERINFO, //
                param.getRedirectUrl()));

        return "/weixin/result";
    }
}